package com.share.wechat.core.service.impl;

import com.share.common.tools.ID.IDutils;
import com.share.wechat.core.entity.Groom;
import com.share.wechat.core.repository.inter.GroomRepository;
import com.share.wechat.core.service.DetailService;
import com.share.wechat.core.service.GroomService;
import com.share.wechat.page.help.PageHelper;
import com.share.wechat.page.help.PageUtil;
import org.apache.log4j.Logger;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class GroomServiceImpl implements GroomService {

    private final Logger logger = Logger.getLogger(this.getClass());
    @Resource
    private GroomRepository groomRepository;
    @Resource
    private DetailService detailService;

    @Override
    public Page<Groom> getByScores(int page, int size) {
        PageUtil pageUtil = PageHelper.getPageUtil(page, size);
        Page<Groom> groomPage = groomRepository.findBySort(pageUtil);
        logger.info("取出的默认推荐为" + groomPage.getContent());
        //TODO  为按照买的情况来取出东西
        //TODO  等订单模块做了 在做这块
        return groomPage;
    }

    @Override
    @Transactional
    public void addGroom(Groom groom) {
        if (StringUtils.isEmpty(groom.getId())) {
            groom.setId(IDutils.getUUID());
        }
        if (detailService.check(groom.getDetailId())) {
            if (logger.isInfoEnabled()) {
                logger.info("添加一个推荐对象为" + groom);
            }
            groomRepository.save(groom);
        }
        if (logger.isInfoEnabled()) {
            logger.info("添加推荐对象成功");
        }

    }

    @Override
    public Page<Groom> getBySort(int dataSort, int page, int size) {
        if (dataSort < 0) {
            logger.info("推荐分数输入为" + dataSort + ":导致查询失败");
            return null;
        }
        PageUtil pageUtil = PageHelper.getPageUtil(page, size, new Sort(Sort.Direction.DESC, "score", "updateTime"));
        return groomRepository.findByDataSort(dataSort, pageUtil);
    }

    @Override
    public List<Groom> findIds(List<String> ids) {


        return null;
    }

    @Override
    public List<Groom> finTopGroom(int page, int size) {
        logger.debug("查询数据的起始页数为" + page);
        PageUtil pageable = PageHelper.getPageUtil(page, size, null);
        Page<Groom> groomList = groomRepository.findBySort(pageable);
        logger.debug("查询到的数据为" + groomList.getContent());
        return groomList.getContent();
    }
}
